<template>
  <div>
    <!-- 头部 -->
    <page-tools :show-before="true">
      <template #before>共{{ page.total }}条记录</template>
      <template #after>
        <el-button
          size="small"
          type="danger"
          :disabled="!checkPermission('employees-export')"
          @click="exportSimple"
        >简单表头导出</el-button>
        <el-button
          size="small"
          type="info"
          :disabled="!checkPermission('employees-export')"
          @click="exportMuti"
        >复杂表头导出</el-button>
        <el-button
          size="small"
          type="success"
          :disabled="!checkPermission('employees-import')"
          @click="$router.push('/import?type=user')"
        >excel导入</el-button>
        <el-button
          size="small"
          type="primary"
          :disabled="!checkPermission('employees-add')"
          @click="addUser"
        >新增员工</el-button>
      </template>
    </page-tools>
    <el-card>
      <el-table :data="list">
        <el-table-column label="序号" type="index" sortable="" />
        <el-table-column prop="username" label="姓名" sortable="" />
        <el-table-column prop="workNumber" label="工号" sortable="" />
        <el-table-column label="照片" sortable="">
          <template slot-scope="{row}">
            <img
              v-imageerror="require('@/assets/common/bigUserHeader.png')"
              :src="row.staffPhoto"
              style="width: 100px; height: 100px;"
              alt=""
              @click="showImg(row.staffPhoto)"
            >
          </template>
        </el-table-column>
        <el-table-column :formatter="formatter" label="聘用形式" prop="formOfEmployment" sortable="" />
        <el-table-column prop="departmentName" label="部门" sortable="" />
        <el-table-column label="入职时间" sortable="">
          <template slot-scope="{ row }">
            <span>{{ row.timeOfEntry | formatDate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="账户状态" sortable="">
          <template slot-scope="{ row }" :value="row.enableState==='1'">
            <!-- 根据当前状态来确定 是否打开开关 -->
            <el-switch :value="row.enableState === 1" />
          </template>
        </el-table-column>
        <el-table-column label="操作" sortable="" fixed="right" width="280">
          <template slot-scope="{row}">
            <el-button
              :id="row.id"
              :disabled="!checkPermission('employees-see')"
              type="text"
              size="small"
              @click="$router.push(`/employees/detail/${row.id}`)"
            >查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="openSetRole(row.id)">角色</el-button>
            <el-button
              type="text"
              :disabled="!checkPermission('employees-del')"
              size="small"
              @click="del(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination
          background
          :page-size="page.size"
          :current-page="page.page"
          :total="page.total"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>
    </el-card>
    <add-user ref="adduser" />
    <!-- 头像预览弹框 -->
    <el-dialog title="" :visible.sync="imgDialogShow">
      <el-row type="flex" justify="center">
        <canvas id="canvas" />
      </el-row>
    </el-dialog>
    <!-- 角色弹框 -->
    <setRole ref="roleForm" />
  </div>
</template>

<script>
import { getEmployeeList, delUser } from '@/api/employees'
import EmployeesEnmu from '@/api/constant/employees'
import addUser from './components/add-user'
import setRole from '@/views/employees/components/set-role'
import { formatDate } from '@/filters'
import QRCode from 'qrcode'
export default {
  components: {
    addUser,
    setRole
  },
  data() {
    return {
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      list: [],
      showDialog: false,
      imgDialogShow: false, // 二维码查看弹框显示控制变量
      imgUrl: '' // 预览头像地址
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 打开角色弹框
    async openSetRole(id) {
      // console.log(id)
      await this.$refs.roleForm.getAllRoleList()
      await this.$refs.roleForm.getUserRoleInfo(id)
      this.$refs.roleForm.showRoleDialog = true
    },
    // 图片点击事件 显示二维码
    showImg(val) {
      if (!val) return this.$message.warning('没有上传头像')
      this.imgDialogShow = true
      this.$nextTick(() => {
        const canvas = document.getElementById('canvas')
        QRCode.toCanvas(canvas, val, (err) => {
          if (err) console.log('生成二维码失败', err)
        })
      })
    },
    // 复杂表头导出
    async exportMuti() {
      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
      const data = rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          }
          if (headers[key] === 'formOfEmployment') {
            return this.formatter('', '', item[headers[key]])
          }
          return item[headers[key]]
        })
      })
      const tHeader = Object.keys(headers)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader, // 表头必填
          data, // 具体数据 必填
          filename: '员工列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx', // 非必填
          multiHeader,
          merges
        })
      })
    },
    // 简单表头导出
    async exportSimple() {
      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      //  1，请求员工列表接口，拿到员工列表数据
      const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
      // 数据处理，处理成excel导出插件所需要的数据形式
      const data = rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          }
          if (headers[key] === 'formOfEmployment') {
            return this.formatter('', '', item[headers[key]])
          }
          return item[headers[key]]
        })
      })
      const tHeader = Object.keys(headers)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader, // 表头必填
          data, // 具体数据 必填
          filename: '员工列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx'// 非必填
        })
      })
    },
    // 添加用户打开弹窗
    addUser() {
      this.$refs.adduser.showDialog = true
    },
    // 删除用户信息
    async del(id) {
      try {
        await this.$confirm('确认删除该用户吗？')
        await delUser(id)
        // 判断是否只有一条数据
        if (this.list.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        this.$message.success('删除成功')
        this.getUserList()
      } catch (error) {
        console.log(error)
      }
    },
    // 聘用形式转换
    formatter(row, column, cellValue, index) {
      const { hireType } = EmployeesEnmu
      const obj = hireType.find(item => item.id === Number(cellValue))
      return obj ? obj.value : '未知'
    },
    // 切页
    changePage(newPage) {
      this.page.page = newPage
      this.getUserList()
    },
    // 获取员工列表
    async getUserList() {
      const { rows, total } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
    }
  }
}
</script>

<style lang='scss' scoped>
</style>
